﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.Dal;
namespace Web
{
    public partial class login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                txUsername.Text = String.Empty;
                txPassword.Text = String.Empty;
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);

            if (String.IsNullOrEmpty(txUsername.Text.Trim()))
            {
                if (scriptManager != null && scriptManager.IsInAsyncPostBack)
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('กรุณากรอกชื่อ');", true);
                else
                    Page.ClientScript.RegisterStartupScript(Page.GetType(), Guid.NewGuid().ToString(), "alert('กรุณากรอกชื่อ');", true);
               
            }
           
            else if (String.IsNullOrEmpty(txPassword.Text))
            {
                if (scriptManager != null && scriptManager.IsInAsyncPostBack)
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('กรุณากรอกรหัสผ่าน');", true);
                else
                    Page.ClientScript.RegisterStartupScript(Page.GetType(), Guid.NewGuid().ToString(), "alert('กรุณากรอกรหัสผ่าน');", true);
               
            }

            else
            {
                DataTable dt = LoginDal.Init().GetUserInfo(txUsername.Text.Trim(), txPassword.Text.Trim());
                try
                {
                    if (dt != null)
                    {
                        if (!String.IsNullOrEmpty(dt.Rows[0]["UID"].ToString()))
                            Response.Redirect("pages/default.aspx");
                    }
                }
                catch (Exception ex)
                {
                    if (!Page.ClientScript.IsStartupScriptRegistered(Page.GetType(), Guid.NewGuid().ToString()))
                    {
                        if (scriptManager != null && scriptManager.IsInAsyncPostBack)
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('ไม่พบชื่อนี้ในระบบ');", true);
                        else
                            Page.ClientScript.RegisterStartupScript(Page.GetType(), Guid.NewGuid().ToString(), "alert('ไม่พบชื่อนี้ในระบบ');", true);
                    }
                }

            }
            
        }

    }
}